﻿namespace Abp.Migration
{
    public class MySqlForeignKeyProvider : IForeignKeyProvider
    {
        public string GetForeignKey(string schemaName, string tableName, string columnName, string refSchemaName, string refTableName, string refColumnName)
        {
            string fkName = string.Format("FK_{0}_{1}_{2}_Ref_{3}_{4}_{5}", schemaName, tableName, columnName, refSchemaName, refTableName, refColumnName);

            return string.Format(@"ALTER TABLE {0} DROP CONSTRAINT {1};
ALTER TABLE {0} ADD CONSTRAINT {1} 
    FOREIGN KEY ({2})
    REFERENCES {3}({4})
;",
                        WrapperWith(GetTableName(schemaName,tableName)),
                        fkName,
                        WrapperWith(columnName),
                        WrapperWith(GetTableName(refSchemaName, refTableName)),
                        WrapperWith(refColumnName)
                        );
          
        }

        private string WrapperWith(string orgin, string start = "`", string end = "`")
        {
            if (string.IsNullOrWhiteSpace(orgin))
                return string.Empty;
            if (!orgin.StartsWith(start))
                orgin = start + orgin;
            if (!orgin.EndsWith(end))
                orgin = orgin + end;
            return orgin;
        }

        private string GetTableName(string schemaName, string tableName)
        {
            string result = WrapperWith(schemaName);
            if (string.IsNullOrWhiteSpace(result))
                result = WrapperWith(tableName);
            else
                result += "_" + WrapperWith(tableName);
            return result;

        }
    }
}
